package wta.mongo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

public class AddUserBasicInfo {

	static Mongo mongo; 
	static DB db;
	static DBCollection coll;
	static SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy");
	
	/**
	 * 经测试，最好是先用List把数据包起来，再进行插入
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		
		mongo = new Mongo("10.110.150.158");
		db = mongo.getDB("china");
		coll = db.getCollection("users");
		
		File dic  = new File("D:\\Now\\ciming\\慈铭数据.20150428\\01");
		String[] list = dic.list(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String name) {
				return name.contains("01个人信息");
			}
		});
		
		for (String string : list) {
			insert(dic.getAbsolutePath() +'\\'+ string);
		}
		
		mongo.close();
	}
	
	public static void insert(String file) throws Exception {
		
		BufferedReader br = new BufferedReader(new FileReader(file));
		
		//get p
		int p = file.lastIndexOf('\\') + 1;
		String cityname = file.substring(p).split("\\.")[0]; 
		
		System.out.println(cityname);
		System.out.println(System.currentTimeMillis());
		
		List<DBObject> objs = new ArrayList<DBObject>();
		
		while(true){
			String userInfo = br.readLine();
			if (userInfo == null) break;
			
			//000400110060300006 女 已婚 67 团体 24-6-10
			String[] info = userInfo.split(" ");
			
			DBObject user = new BasicDBObject();
			short sex = -1;
			short marry = -1;
			short age = -1;
			boolean team = false;
			
			//判断性别
			if (info[1].equals("男"))
				sex = 0;
			else if (info[1].equals("女"))
				sex = 1;
			else System.out.println(info[1]);
			
			//判断婚否
			if (info[2].equals("未婚"))
				marry = 0;
			else if (info[2].equals("已婚"))
				marry = 1;
			
			//判断年龄
			try{
				age = Short.parseShort(info[3]);
			}catch(NumberFormatException e){}
			

			if (info[4].equals("团体"))
				team = true;
			else if (info[4].equals("个人")){}
			else System.err.println(info[4]);

			Date date = new Date();
			date = sdf.parse(info[5]);
			
			//执行插入操作
			user.put("uid", info[0]);
			user.put("sex", sex);
			user.put("marry", marry);
			user.put("age", age);
			user.put("team", team);
			user.put("date", date);
			user.put("city", cityname);
			
			objs.add(user);
		}
		
		br.close();
		System.out.println(objs.size());
		coll.insert(objs);
		System.out.println(System.currentTimeMillis());
	}

}
